package postman

import (
	"apibe/grpc/rome/v1/factory"
	"apibe/grpc/rome/v1/factory/tools"
	"encoding/json"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

// todo 对每个接口进行监控
// 监控：API可用性监控、API响应时间分析、API正确性分析、API被调用次数记录、API错误返回报警
// POSTMAN脚本录入、监控任务数、历史快照、监控频率、自定义告警、多用户管理、权限管理、消息推送、URL回调

// Postman
// 生成便于传递的postman接口文件
type Postman struct {
	Info struct {
		PostmanID string `json:"_postman_id"`
		Name      string `json:"name"`
		Schema    string `json:"schema"`
	} `json:"info"`
	Item []item `json:"item"`
}

type item struct {
	Name    string `json:"name"`
	Request struct {
		Method string   `json:"method"`
		Header []header `json:"header"`
		Body   body     `json:"body"`
		Url    string   `json:"url"`
	} `json:"request"`
	Response []interface{} `json:"response"`
}
type header struct {
	Key   string `json:"key"`
	Value string `json:"value"`
	Type  string `json:"type"`
}
type body struct {
	Mode    string `json:"mode"`
	Raw     string `json:"raw"`
	Options struct {
		Raw struct {
			Language string `json:"language"`
		} `json:"raw"`
	} `json:"options"`
}

func (p *Postman) New(name string) *Postman {
	p.Info.PostmanID = primitive.NewObjectID().Hex()
	p.Info.Name = name
	p.Info.Schema = "https://schema.getpostman.com/json/collection/v2.0.0/collection.json"
	return p
}

func (p *Postman) GetPostman(url string, token string, ds *[]factory.Design) {
	for _, design := range *ds {
		reqMap := make(map[string]string)
		for _, argument := range design.Data.Argument {
			if argument.ArgumentOpinion != tools.Static {
				reqMap[argument.Key] = argument.Value
			}
		}
		bytes, _ := json.Marshal(reqMap)
		itm := &item{}
		itm.Name = design.ApiName
		itm.Request.Url = url + "/v1/design/process/" + design.ApiName
		itm.Request.Method = "POST"
		itm.Request.Header = append(itm.Request.Header, header{"debug", "APIBE", "text"}, header{"Authorization", token, "text"})
		itm.Request.Body = body{"raw", string(bytes), struct {
			Raw struct {
				Language string `json:"language"`
			} `json:"raw"`
		}(struct {
			Raw struct {
				Language string `json:"language"`
			}
		}{Raw: struct {
			Language string `json:"language"`
		}(struct{ Language string }{Language: "json"})})}
		itm.Response = []interface{}{}
		p.Item = append(p.Item, *itm)
	}
}

// 代码生成器
// 前后端统一的代码生成器：
